import vue from 'rollup-plugin-vue';
import {nodeResolve} from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import json from "@rollup/plugin-json";
import postcss from 'rollup-plugin-postcss'
import babel from "@rollup/plugin-babel";
import {DEFAULT_EXTENSIONS} from "@babel/core";
import {terser} from "rollup-plugin-terser";
import path from "path";
import AutoImport from 'unplugin-auto-import/webpack'
import Components from 'unplugin-vue-components/webpack'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
const fs = require('fs');

// packages 文件夹路径
const root = path.resolve(__dirname,'..', 'packages')


export const getPlugins = () => {
    return [
        vue(),
        AutoImport({
            resolvers: [ElementPlusResolver()]
        }),
        Components({
            resolvers: [ElementPlusResolver()]
        }),
        postcss({
            plugins: [require('autoprefixer')],
            // 把 css 插入到 style 中
            inject: true,
            // 抽离单独的css文件
            extract: 'index.css',
            // Minimize CSS, boolean or options for cssnano.
            minimize: true,
            // Enable sourceMap.
            sourceMap: false,
            // This plugin will process files ending with these extensions and the extensions supported by custom loaders.
            extensions: ['.sass', '.less', '.scss', '.css']
        }),
        babel({
            exclude: 'node_modules/**',
            babelHelpers: 'runtime',
            extensions: [...DEFAULT_EXTENSIONS, '.vue']
        }),
        nodeResolve({
            mainField: ['jsnext:main', 'browser', 'module', 'main'],
            browser: true,
            extensions: ['.mjs','.js', '.json', '.jsx', '.vue'],
        }),
        commonjs(),
        json(),
        
        // postcss({
        //     plugins: [require('autoprefixer')],
        //     // 把 css 插入到 style 中
        //     inject: true,
        //     // 抽离单独的css文件
        //     extract: 'index.css',
        //     // Minimize CSS, boolean or options for cssnano.
        //     minimize: true,
        //     // Enable sourceMap.
        //     sourceMap: false,
        //     // This plugin will process files ending with these extensions and the extensions supported by custom loaders.
        //     extensions: ['.sass', '.less', '.scss', '.css']
        // }),
        terser({toplevel: false})
    ]
}

/**
 * 将所有组件打包为一个文件
 * @param item
 * @param targetItem
 * @returns {{output: [{file: string, sourcemap: boolean, globals: {vue: string, "element-plus": string}, name: string, format: string},{file: string, sourcemap: boolean, globals: {vue: string, "element-plus": string}, name: string, format: string}], input: string, external: string[], plugins: *, onwarn: onwarn}}
 */
export const buildModules = (item, targetItem = null)=>{
    const pkg = require(path.resolve(root, item, 'package.json'))
    return {
        input: path.resolve(root, item, 'index.js'),//入口文件
        output: [
            {
                name: 'index',
                file: path.resolve(root, targetItem || item , pkg.main),
                format: 'cjs',
                sourcemap: false,
                globals: {
                    vue: 'vue',
                    'element-plus': 'element-plus'
                }
            },
            {
                name: 'index.module',
                file: path.resolve(root, targetItem || item , pkg.module),
                format: 'esm',
                sourcemap: false,
                globals: {
                    vue: 'vue',
                    'element-plus': 'element-plus'
                }
            }
        ],
        onwarn: function (warning) {
            if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'CIRCULAR_DEPENDENCY') {
                return
            }
            console.error(`(!) ${warning.message}`)
        },
        plugins: getPlugins(),
        external: Object.keys(require(path.join(root, item, 'package.json'))?.peerDependencies || {})
    }
}


export const buildPreserveModules = (item, targetItem = null)=>{
    const pkg = require(path.resolve(root, item, 'package.json'))
    const epRoot =  path.resolve(root, item)
    const pathLib = path.resolve(root, item, 'dist/lib')
    const pathEs = path.resolve(root, item, 'dist/es')
    return {
        input: path.resolve(root, item, 'index.js'),//入口文件
        output: [
            {
                name: 'index',
                dir: pathLib,
                format: 'cjs',
                sourcemap: false,
                globals: {
                    vue: 'vue',
                    'element-plus': 'element-plus'
                },
                preserveModules: true, // 保留模块结构
                preserveModulesRoot: epRoot, // 将保留的模块放置在根路径下的此路径下
                entryFileNames: `[name].js`,
            },
            {
                name: 'index.module',
                dir: pathEs,
                format: 'esm',
                sourcemap: false,
                globals: {
                    vue: 'vue',
                    'element-plus': 'element-plus'
                },
                preserveModules: true, // 保留模块结构
                preserveModulesRoot: epRoot, // 将保留的模块放置在根路径下的此路径下
                entryFileNames: `[name].mjs`,
            }
        ],
        onwarn: function (warning) {
            if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'CIRCULAR_DEPENDENCY') {
                return
            }
            console.error(`(!) ${warning.message}`)
        },
        plugins: getPlugins(),
        external: Object.keys(require(path.join(root, item, 'package.json'))?.peerDependencies || {})
    }
}
/**
 * 打包语言包
 * @returns {{output: [{file: *, sourcemap: boolean, name: string, format: string},{file: *, sourcemap: boolean, name: string, format: string}], input: *, external: string[], plugins: *, onwarn: function(*): void}[]}
 */
export const buildLocale =  () => {
    const pathStr = path.resolve(root, 'locale/lang')
    const files = fs.readdirSync(pathStr)
    return files.map(file => {
        return formatLocaleTask(file.split('.')[0])
    })
}


/**
 * 组件分别打包
 * @param item
 * @returns {*}
 */
export const buildModulesForItem = (item)=> {
    const pathStr = path.resolve(root, item)
    let files = excludeFiles(fs.readdirSync(pathStr))
    console.log(files)
    return files.map(file => {
        return formatTask(item, file)
    })
}


export const excludeFiles = (files) => {
    const excludes = ['node_modules', 'test', 'mock', 'gulpfile', 'dist', 'json', '.js','.md', 'theme-chalk', 'hooks']
    return files.filter(
        (path) => !excludes.some((exclude) => path.includes(exclude))
    )
}


const pkg = {
    main: 'index.js',
    module: 'index.module.js',
}

const formatTask = (dir, fileName) => {
    const pathLib = path.resolve(root, dir, 'dist/lib')
    const pathEs = path.resolve(root, dir, 'dist/es')
    const epRoot =  path.resolve(root, dir)
    return {
        input: path.resolve(root, dir, fileName, 'index.js'),//入口文件
        output: [
            {
                dir: pathLib,
                format: 'cjs',
                sourcemap: false,
                globals: {
                    vue: 'vue',
                    'element-plus': 'element-plus'
                },
                preserveModules: true, // 保留模块结构
                preserveModulesRoot: epRoot, // 将保留的模块放置在根路径下的此路径下
                entryFileNames: `[name].js`,
            },
            {
                dir: pathEs,
                format: 'esm',
                sourcemap: false,
                globals: {
                    vue: 'vue',
                    'element-plus': 'element-plus'
                },
                preserveModules: true, // 保留模块结构
                preserveModulesRoot: epRoot,  //将保留的模块放置在根路径下的此路径下
                entryFileNames: `[name].mjs`,
            }
        ],
        onwarn: function (warning) {
            if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'CIRCULAR_DEPENDENCY') {
                return
            }
            console.error(`(!) ${warning.message}`)
        },
        plugins: getPlugins(),
        external: Object.keys(require(path.join(root, dir, 'package.json'))?.peerDependencies || {})
    }
}


// element-plus/es/locale/lang/zh-cn
// dir: 'dist/es/locale/lang'
const formatLocaleTask = (fileName) => {
    const dir = 'locale'
    const dir1 = 'lang'
    const pathLib = path.resolve(root,  dir, 'dist/lib', dir , `${fileName}.js`)
    const pathEs = path.resolve(root, dir, 'dist/es', dir , `${fileName}.mjs`)
    
    return {
        input: path.resolve(root, dir, dir1, fileName),//入口文件
        output: [
            {
                name: 'index',
                file: pathLib,
                format: 'cjs',
                sourcemap: false,
            },
            {
                name: 'index.module',
                file: pathEs,
                format: 'esm',
                sourcemap: false,
            }
        ],
        onwarn: function (warning) {
            if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'CIRCULAR_DEPENDENCY') {
                return
            }
            console.error(`(!) ${warning.message}`)
        },
        plugins: getPlugins(),
        external: Object.keys(require(path.join(root, 'locale', 'package.json'))?.peerDependencies || {})
    }
}